package com.zwmuzhi.springcloud.controller;

import com.netflix.loadbalancer.IRule;
import com.zwmuzhi.springcloud.entities.CommonResult;
import com.zwmuzhi.springcloud.entities.Payment;
import com.zwmuzhi.springcloud.loadbalanced.MyLoadBalanced;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

/**
 * <h3>cloudLearn</h3>
 * <p></p>
 *
 * @author : zwmuzhi
 * @date : 2020-11-14 15:41
 **/
@RestController
@RequestMapping("order")
@Slf4j
public class OrderController {
    private final static String paymentBaseUrl = "http://CLOUD-PAYMENT-SERVICE/payment/";

    @Resource
    RestTemplate restTemplate;

    @Resource
    DiscoveryClient discoveryClient;

    @Resource
    MyLoadBalanced myLoadBalanced;

    /**
     * 创建
     * @param payment
     * @return
     */
    @PostMapping("")
    public CommonResult create(@RequestBody Payment payment){
        log.info("create payment url:{},payment:{}",paymentBaseUrl,payment);
        return restTemplate.postForObject(paymentBaseUrl,payment,CommonResult.class);
    };

    /**
     * 根据ID查询
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id){
        log.info("getPaymentById url:{}",paymentBaseUrl+id);
        return restTemplate.getForObject(paymentBaseUrl+id,CommonResult.class);
    };

    /**
     * 根据ID查询LoadBalanced
     * @param id
     * @return
     */
    @GetMapping("/balanced/{id}")
    public CommonResult getPaymentByIdBalanced(@PathVariable("id") Long id){

        // 获取所有服务
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        // 根据轮循机制获取当前应该调用的服务实例
        ServiceInstance instance = myLoadBalanced.instance(instances);
        // 获取URI路径
        URI uri = instance.getUri();

        log.info("getPaymentByIdBalanced url:{}",uri.toString()+id);
        return restTemplate.getForObject(uri.toString()+"/payment/"+id,CommonResult.class);
    };



}
